import socket
import threading
import file_system

class fs_PServer:
    def __init__(self, host="0.0.0.0", port=8888):

        self.host = host
        self.port = port
        self.server_socket = None
        self.client_sockets = []  # 存储所有客户端连接（用于广播）

    def start(self):

        # 1. 创建 Socket
        self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        # 2. 绑定 IP 和端口
        self.server_socket.bind((self.host, self.port))

        # 3. 开始监听
        self.server_socket.listen(5)
        print(f"服务器启动，监听 {self.host}:{self.port}...")

        # 4. 接受客户端连接（多线程）
        while True:
            client_socket, addr = self.server_socket.accept()
            print(f"客户端 {addr} 已连接")
            self.client_sockets.append(client_socket)

            # 为每个客户端创建线程
            thread = threading.Thread(
                target=self.handle_client,
                args=(client_socket, addr)
            )
            thread.daemon = True  # 主线程退出时自动结束
            thread.start()

    def handle_client(self, client_socket, addr):
        """处理客户端连接（持续接收并执行多个指令）"""
        try:
            while True:  # 保持连接循环
                # 阻塞等待指令（直到客户端发送数据或断开）
                data = client_socket.recv(1024)
                if not data:  # 客户端主动断开连接
                    print(f"客户端 {addr} 关闭连接")
                    break

                # 处理指令
                try:
                    args = data.decode('utf-8').strip()
                    print(f"执行指令: {args}")

                    # 执行指令（单次执行）
                    result = self.execute_command(args)

                    # 返回执行结果
                    if result:
                        response = '操作成功！！'
                    else:
                        response = '操作失败...请检查是否符合操作规范'

                    client_socket.send(response.encode('utf-8'))

                except UnicodeDecodeError:
                    client_socket.send("错误：非UTF-8编码".encode('utf-8'))
                except Exception as e:
                    client_socket.send(f"错误：{str(e)}".encode('utf-8'))

        except ConnectionResetError:
            print(f"客户端 {addr} 异常断开")
        finally:
            client_socket.close()
            print(f"释放客户端 {addr} 的资源")
            if client_socket in self.client_sockets:
                self.client_sockets.remove(client_socket)

    def execute_command(self, command):
        """执行客户端发送的命令（返回执行结果）"""
        # 这里是实际执行命令的逻辑
        return file_system .main(command )


    def stop(self):
        """关闭服务器"""
        for sock in self.client_sockets:
            sock.close()
        self.server_socket.close()


if __name__ == "__main__":
    server = fs_PServer()
    try:
        server.start()
    except (KeyboardInterrupt, OSError):  # 捕获 accept() 抛出的异常
        server.stop()